package com.penghaonan.appframework.utils

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import com.penghaonan.appframework.AppDelegate

object MessageCenter {

    private val receiverList = WeakObservableList<ReceiverWrapper>()

    @JvmStatic
    fun register(receiver: Receiver, msg: String) {
        register(receiver, setOf(msg))
    }

    @JvmStatic
    fun register(receiver: Receiver, msgList: List<String>) {
        register(receiver, msgList.toSet())
    }

    @JvmStatic
    fun register(receiver: Receiver, msgList: Set<String>) {
        val receiverWrapper = ReceiverWrapper(receiver, msgList.toSet())
        synchronized(receiverList) {
            receiverList.addListener(receiverWrapper)
        }
    }

    @JvmStatic
    fun unregister(receiver: Receiver) {
        synchronized(receiverList) {
            receiverList.iterate(object : WeakObservableList.OnIterator<ReceiverWrapper>() {
                override fun onIterator(item: ReceiverWrapper?): Boolean {
                    if (item?.receiver == receiver) {
                        remove()
                    }
                    return false
                }
            })
        }
    }

    @JvmOverloads
    @JvmStatic
    fun send(msg: String, bundle: Bundle? = null, post: Boolean = true) {
        if (post) {
            AppDelegate.post {
                sendSync(msg, bundle)
            }
        } else {
            sendSync(msg, bundle)
        }
    }

    private fun sendSync(msg: String, bundle: Bundle?) {
        synchronized(receiverList) {
            receiverList.iterate(object : WeakObservableList.OnIterator<ReceiverWrapper>() {
                override fun onIterator(item: ReceiverWrapper?): Boolean {
                    if (item?.msgSet?.contains(msg) == true) {
                        item.receiver.onReceiver(msg, bundle)
                    }
                    return false
                }
            })
        }
    }

    interface Receiver {
        fun onReceiver(msg: String, bundle: Bundle? = null)
    }

    private class ReceiverWrapper(
        val receiver: Receiver,
        val msgSet: Set<String>
    ) : Receiver {
        override fun onReceiver(msg: String, bundle: Bundle?) {
            receiver.onReceiver(msg, bundle)
        }

    }
}